package jmine.tec.performance.test;

import java.util.TimerTask;

/**
 * Class to monitor the use of memory. Use a {@link java.util.Timer#schedule(TimerTask, long, long)} to schedule the memory check.
 * 
 * @author bruno.ortiz
 */
public class MemoryMonitor extends TimerTask {

    private float maxMemoryUsage = 0;

    private float numberOfMemoryChecks = 0;

    private float meanOfMemoryUsage = 0;

    private MemoryUsageCalculator memCalc = new MemoryUsageCalculator();

    /**
     * {@inheritDoc}
     */
    @Override
    public void run() {
        float actualMemomyUsage = memCalc.getUsedMemory();
        this.numberOfMemoryChecks++;
        this.meanOfMemoryUsage =
                (((this.numberOfMemoryChecks - 1) / this.numberOfMemoryChecks) * this.meanOfMemoryUsage)
                        + (actualMemomyUsage / this.numberOfMemoryChecks);
        if (actualMemomyUsage > maxMemoryUsage) {
            maxMemoryUsage = actualMemomyUsage;
        }

    }

    /**
     * @return The max memory usage.
     */
    public float getMaxMemoryUsage() {
        return this.maxMemoryUsage;
    }

    /**
     * @return The mean of memory usage.
     */
    public float getMeanOfMemoryUsage() {
        return this.meanOfMemoryUsage;
    }
}
